<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type {
  OnActionClickParams,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';
import type { DictApi, ToolTypeApi } from '#/api';

import { reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { VxeButton } from '@vben/plugins/vxe-table';

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { DictResp } from '#/api';
import {
  deleteClient,
  getWorkshopList,
  mdClientApi,
} from '#/api/mes/md/client';
import {
  getToolBarBtns,
  messageError,
  messageSuccess,
  PopMsg,
  setToolBarBtnDefaultDisabled,
  updateToolbarButtonStatus,
} from '#/utils';

import clientAdd from './clientAdd.vue';
import clientAmendTabs from './clientAmendTabs.vue';

const [clientApi, modalApi] = useVbenModal({
  connectedComponent: clientAdd,
  showConfirmButton: false,
  showCancelButton: false,
});

const [clientAmendTabsApi, TabsmodalApi] = useVbenModal({
  connectedComponent: clientAmendTabs,
  showConfirmButton: false,
  showCancelButton: false,
});

const sys_yes_no = reactive<DictApi.SelectOption[]>([]);
const mes_client_type = reactive<DictApi.SelectOption[]>([]);

DictResp(['sys_yes_no', 'mes_client_type']).then((res) => {
  if (res.mes_client_type) {
    mes_client_type.push(...res.mes_client_type);
  }
  if (res.sys_yes_no) {
    sys_yes_no.push(...res.sys_yes_no);
  }
});

const selectedRow = ref<ToolTypeApi.Row[]>([]);
const initData = {
  toolTypeId: null,
  toolTypeCode: '',
  toolTypeName: '',
  codeFlag: 'Y',
  maintenType: null,
  maintenPeriod: null,
  remark: '',
};
selectedRow.value = [initData];

interface RowType {
  searchValue: null;
  createBy: string;
  createTime: Date;
  updateBy: string;
  updateTime: Date | null;
  remark: string;
  params: any;
  clientId: number;
  clientCode: string;
  clientName: string;
  clientNick: null | string;
  clientEn: null | string;
  clientDes: null | string;
  clientLogo: null | string;
  clientType: string;
  address: null | string;
  website: null | string;
  email: null | string;
  tel: null | string;
  contact1: null | string;
  contact1Tel: null | string;
  contact1Email: null | string;
  contact2: null | string;
  contact2Tel: null | string;
  contact2Email: null | string;
  creditCode: null | string;
  enableFlag: string;
  attr1: null;
  attr2: null;
  attr3: number;
  attr4: number;
  attr5: null;
}
const buttons = getToolBarBtns();
buttons.value.push(
  {
    name: '导出',
    code: 'export',
    status: 'warning',
    icon: 'vxe-icon-download',
  },
  {
    name: '导入',
    code: 'import',
    status: 'success',
    icon: 'vxe-icon-upload',
  },
);
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入客户编码',
      },
      fieldName: 'productName',
      label: '客户编码',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入客户名称',
      },
      fieldName: 'price',
      label: '客户名称',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入客户简称',
      },
      fieldName: 'clientNick',
      label: '客户简称',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入客户英文名称',
      },
      fieldName: 'clientEn',
      label: '客户英文名称',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: sys_yes_no,
        placeholder: '是否启用',
      },
      fieldName: 'color',
      label: '是否启用',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};
// const buttons = getToolBarBtns();
const gridOptions: VxeGridProps<RowType> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    { align: 'left', title: '', type: 'checkbox', width: 100 },
    {
      field: 'clientCode',
      title: '客户编码',
      cellRender: { name: 'CellButtonInfo', props: { onClick: onEdit } },
    },
    { field: 'clientName', title: '客户名称' },
    { field: 'clientNick', title: '客户简称' },
    {
      field: 'clientType',
      title: '客户类型',
      formatter: ({ cellValue }) => {
        const item = mes_client_type.find((item) => item.value === cellValue);
        return item?.label || '';
      },
    },
    { field: 'tel', title: '客户电话' },
    { field: 'contact1', title: '联系人' },
    { field: 'contact1Tel', title: '联系人电话' },
    {
      field: 'enableFlag',
      title: '是否启用',
      cellRender: { name: 'CellTag' },
      // formatter: ({ cellValue }) => {
      //   return cellValue === '1' ? '是' : '否';
      // },
    },
    {
      title: '操作',
      width: 150,
      slots: { default: 'operate' },
    },
  ],
  virtualYConfig: { enabled: true },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    slots: {
      // 自定义分页器
    },
    // 每页显示数量选择
    pageSizes: [10, 20, 50, 100],
    // 分页布局
    layouts: [
      'PrevJump',
      'PrevPage',
      'Number',
      'NextPage',
      'NextJump',
      'Sizes',
      'FullJump',
      'Total',
    ],
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const res = await getWorkshopList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return {
          total: res.total,
          items: res.rows,
        };
      },
    },
  },
  toolbarConfig: {
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    // refresh: true,
    refresh: { code: 'query' },
    buttons: buttons.value,
  },
};

// 控制modal的响应式变量
const showPopup = ref(false);

/**
 * 编辑
 * @param row
 */
function onEdit(row: mdClientApi.Row) {
  selectedRows.value = [row];
  showPopup.value = true;
  TabsmodalApi.setState({ title: '查看客户' }).setData(row).open();
}

/**
 * 创建
 */
function onAdd() {
  // selectedRows.value = [initData];
  // showPopup.value = true;
  modalApi.setData({ row: initData }).open();
}

/**
 * 删除
 * @param row
 */

function onDelete(data: mdClientApi.Row | mdClientApi.Row[]) {
  const ids = Array.isArray(data)
    ? data.map((item) => item.clientId)
    : [data.clientId];
  const idString = ids.join(',');
  PopMsg(`确定要删除客户编号编号为【${idString}】的数据吗？`, '提示', 'warn')
    .then(() =>
      deleteClient(idString)
        .then(() => {
          messageSuccess(`删除成功`);
          refreshGrid();
        })
        .catch((error) => {
          messageError(error);
        }),
    )
    .catch(() => {
      // 用户点击取消
      message.info('已取消删除');
    });
}

// 存储选中行的响应式变量
const selectedRows = ref<any[]>([]);

// 表格事件
const gridEvents: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    // console.warn(code);
    switch (code) {
      case 'myAdd': {
        // 新增逻辑
        onAdd();
        modalApi
          .setState({
            title: '添加客户',
          })
          .open();
        break;
      }
      case 'myDel': {
        if (selectedRows.value.length > 0) {
          onDelete(selectedRows.value);
        }
        break;
      }
      case 'myEdit': {
        // 修改逻辑
        onEdit(selectedRows.value[0]);
        TabsmodalApi.setState({
          title: '添加客户',
        }).open();
        break;
      }
      default: {
        break;
      }
    }
    updateToolbarButtonStatus(selectedRows); // 更新按钮状态
  },
  checkboxChange() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
    setToolBarBtnDefaultDisabled(buttons, selectedRows.value.length);
  },
  checkboxAll() {
    selectedRows.value = gridApi?.grid?.getCheckboxRecords();
    setToolBarBtnDefaultDisabled(buttons, selectedRows.value.length);
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

/**
 *
 * 处理表格操作列点击事件的函数
 *
 * @param  - 包含操作代码和行数据的对象
 */

function onActionClick({ code, row }: OnActionClickParams<mdClientApi.Row>) {
  switch (code) {
    case 'myDel': {
      onDelete(row);
      break;
    }
    case 'myEdit': {
      onEdit(row);
      break;
    }
  }
  updateToolbarButtonStatus(selectedRows); // 更新按钮状态
}

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}
</script>

<template>
  <div class="vp-raw w-full">
    <Grid>
      <template #operate="{ row }">
        <VxeButton
          mode="text"
          status="primary"
          icon="vxe-icon-signature"
          @click="
            () =>
              TabsmodalApi.setState({ title: '修改客户' }).setData(row).open()
          "
        >
          修改
        </VxeButton>
        <VxeButton
          mode="text"
          status="error"
          icon="vxe-icon-delete"
          @click="onActionClick({ code: 'myDel', row })"
        >
          删除
        </VxeButton>
      </template>
    </Grid>
    <clientApi class="w-[900px]" @success="refreshGrid" />
    <clientAmendTabsApi class="h-[1000px] w-[900px]" @success="refreshGrid" />
  </div>
</template>
